/*
 * gpio.c
 *
 *  Created on: Feb 8, 2013
 *      Author: bfakhri
 */

#include "gpio.h"
//Accesses the SETDD register and returns the state of pin p_pin (0 or 1).
int gpio_port_dd_get_pin_state(int p_pin)
{
	// Decide whether the pin is high or low and return that value
	// Will return a nonzero value if that position is high 
	return ((((~MCF_GPIO_SETDD | 1 << (3+p_pin)) & MCF_GPIO_SETDD)) >> (3+p_pin)); 
}
//Configures PDDPAR and DDRDD so pin p_pin of port DD is in GPIO function and the
//pin data direction is input. FOR DIP SWITCHES
void gpio_port_dd_init()
{
	//Sets the corresponding portDD register values to 0 (for GPIO)
	MCF_GPIO_PDDPAR &= ~(MCF_GPIO_PDDPAR_DDATA0_DDATA0 | MCF_GPIO_PDDPAR_DDATA1_DDATA1 | MCF_GPIO_PDDPAR_DDATA2_DDATA2 | MCF_GPIO_PDDPAR_DDATA3_DDATA3); 

	//Sets corresponding DDRDD values to 0 for input (these correspond to the port DD[7:4) which control the switches
	MCF_GPIO_DDRDD &= ~(MCF_GPIO_DDRDD_DDRDD7 | MCF_GPIO_DDRDD_DDRDD6 | MCF_GPIO_DDRDD_DDRDD5 | MCF_GPIO_DDRDD_DDRDD4);
}

//Accesses the SETTC register and returns the state of pin p_pin (0 or 1).
int gpio_port_tc_get_pin_state(int p_pin)
{
	// Decide whether the pin is high or low and return that value
	// Will return a nonzero value if that position is high 
	return ((((~MCF_GPIO_SETTC | 1 << p_pin) & MCF_GPIO_SETTC)) >> p_pin);
}

//Configures PTCPAR and DDRTC so port TC is in GPIO function and the pin data
//direction is output.
void gpio_port_tc_init()
{
	// Configures PTCPAR LED pins as GPIO pins
	MCF_GPIO_PTCPAR = MCF_GPIO_PTCPAR_PTCPAR0(MCF_GPIO_PTCPAR_DTIN0_GPIO) |
	                        MCF_GPIO_PTCPAR_PTCPAR1(MCF_GPIO_PTCPAR_DTIN1_GPIO) |
	                        MCF_GPIO_PTCPAR_PTCPAR2(MCF_GPIO_PTCPAR_DTIN2_GPIO) |
	                        MCF_GPIO_PTCPAR_PTCPAR3(MCF_GPIO_PTCPAR_DTIN3_GPIO);
	// Configures DDRTC as output
	MCF_GPIO_DDRTC = MCF_GPIO_DDRTC_DDRTC0 | MCF_GPIO_DDRTC_DDRTC1 | MCF_GPIO_DDRTC_DDRTC2
	                        | MCF_GPIO_DDRTC_DDRTC3;
}

//Accesses the SETTC register to set the state of pin p_pin to p_state.
void gpio_port_tc_set_pin_state(int p_pin ,int p_state)
{
	if(p_state != 0)
	{
		MCF_GPIO_SETTC |= 1 << p_pin;	// Sets the state of the pin to 1 
	}
	else
	{
		MCF_GPIO_CLRTC &= ~(1 << p_pin);	// Clears the pin at p_pin
	}
}
